<script setup lang="ts">
import { watchEffect, ref, reactive, defineComponent } from 'vue'
import { componentMap } from '@/util/menu'
import { ElMessage } from 'element-plus'
const props = defineProps<{
  path: string
}>()

let Comp = reactive(defineComponent({}))
const loading = ref(true)
const err = ref(false)
async function loadComp() {
  if (props.path === '') {
    return
  }
  try {
    loading.value = true
    err.value = false
    const fun = componentMap.get(props.path!)
    if (!fun) {
      ElMessage.error('找不到组件')
      return
    }
    // let url = fun.toString().match(/import\(".*"\)/)![0]!
    // url = url.replace('import("', '').replace('")', "")
    // if (url.split('?').length > 1) {
    //   url = url + '&' + Math.random()
    // }
    // else {
    //   url = url + '?' + Math.random()
    // }
    // console.log(url);

    if (typeof fun === 'function') {
      // let f = () => import(/* @vite-ignore */`${url}`)
      Comp = (await fun()).default
      // console.log(Comp);
    } else {
      ElMessage.error('组件加载出错')
      err.value = true
    }
  } catch {
    err.value = true
  } finally {
    loading.value = false
  }
}
watchEffect(() => {
  loadComp()
})
</script>
<template>
  <div>
    <slot name="load" v-if="loading"> 正在加载组件 </slot>
    <slot name="err" v-if="err">
      页面所需的组件加载出错了
      <button @click="loadComp">重新加载</button>
    </slot>
    <Comp v-if="!loading && !err"></Comp>
  </div>
</template>
